package com.soriya.nestlive.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtil {

    private static final long EXPIRE = 1000L * 60 * 60 * 24 * 99999; // 过期时间
//    private static final long EXPIRE = 1000 * 30; // 过期时间
    private static final String key = "SoRiya"; // 密钥

    public static String getToken(Long id, String name) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT") // 设置头信息: token类型
                .setHeaderParam("alg", "HS256") // 设置头信息: 加密方式
                .setSubject("enjoy") // 设置主题
                .setIssuedAt(new Date()) // 设置发布时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) // 设置过期时间

                // 设置载荷
                .claim("id", id)
                .claim("nickName", name)

                .signWith(SignatureAlgorithm.HS256, key) // 加密
                .compact(); // 生成Token
    }

    public static boolean checkToken(String token) {
        if (StringUtils.isEmpty(token)) return false;
        try {
            Jwts.parser().setSigningKey(key).parseClaimsJws(token);
        } catch(Exception e) {
            return false;
        }
        return true;
    }

    public static boolean checkToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        return checkToken(token);
    }

    public static Long getMemberIdByToken(String token) {
        if (StringUtils.isEmpty(token)) return 0L;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(key).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body.get("id", Long.class);
    }

    public static Long getMemberIdByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        return getMemberIdByToken(token);
    }


}
